/**
 * @description channel service
 */

const _ = require('lodash')
const WorksModel = require('../model/work')

/**
 * 创建渠道
 * @param {string} id workId
 * @param {object} data 渠道数据
 */
async function createChannel(id, data = {}) {
  const result = await WorksModel.findOneAndUpdate({ id }, data, { new: true })
  return result
}

/**
 * 删除渠道
 * @param {*} id channel ID
 */
async function deleteChannel(id) {
  const result = await WorksModel.findOneAndUpdate(
    { 'channels.id': id },
    // $pull 删除 channels 数组特定的项
    { $pull: { channels: { id } } },
    { new: true }
  )
  return result
}

/**
 * 更新渠道
 * @param {*} id channel ID
 * @param {object} data 要更新的数据
 */
async function updateChannel(id, data = {}) {
  if (_.isEmpty(data)) return null

  const result = await WorksModel.findOneAndUpdate({ 'channels.id': id }, data)
  return result
}

/**
 * 查询渠道
 * @param {object} whereOpt 查询条件
 */
async function findChannels(whereOpt = {}) {
  const workData = await WorksModel.findOne(whereOpt)
  if (workData) {
    const { channels } = workData
    return {
      count: (channels && channels.length) || 0,
      list: channels || []
    }
  }
  return null
}

module.exports = {
  createChannel,
  deleteChannel,
  updateChannel,
  findChannels
}
